package net.sxnic.workflow.whimpl;

import net.sxnic.ugr.context.AppContext;
import net.sxnic.workflow.conf.WfConfigUtils;
import net.sxnic.workflow.context.WfContextImpl;
import net.sxnic.workflow.handler.AbstractHandler;
import net.sxnic.workflow.handler.HandlerExt;
import net.sxnic.workflow.handler.WfHandlerException;
import net.sxnic.workflow.wfentity.WfEntity;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 保存实体
 * 
 * @author 孙宇飞
 * 
 */
public class SaveEntityHandler extends AbstractHandler<WfEntity> implements
		HandlerExt<WfEntity> {

	private static Logger logger = LoggerFactory
			.getLogger(SaveEntityHandler.class);

	public SaveEntityHandler(WfContextImpl<WfEntity> context) {
		super(context);
	}

	@Override
	public void editExecute() throws WfHandlerException {

	}

	@Override
	public void saveExecute() throws WfHandlerException {
		opt();		
		logger.debug("===invoke==save===success====entityId==="
				+ context.getEntityId());
	}

	@Override
	public void viewExecute() throws WfHandlerException {

	}

	@Override
	public void submitExecute() throws WfHandlerException {
		opt();
		logger.debug("===invoke==submit===success====entityId==="
				+ context.getEntityId());
	}

	private void opt() {
		try {
			//文件的拟稿人如果没有的话，则把当前登录人员，写入。
			if(StringUtils.isBlank(context.getEntity().getInitiator())){
				String startNodeName = WfConfigUtils.findStartNodeName(context
						.getProcessName());
				if (startNodeName.equals(context.getTaskName())) {
					context.getEntity().setInitiator(AppContext.getUserName());
				}
			}		
			
		} catch (Exception e) {
			e.printStackTrace();
		}

		context.getWfenManager().save(context.getEntity());
		context.setEntityId(context.getEntity().getId());
	}
}
